var q = require("../../utils/question.js"), n = "random", r = "exam", s = 1, app = getApp();

var util = require('../../utils/util.js');
let md5 = require('../../utils/md5.js').md5;
Page({

  data: {
    circular: true,
    currIndex: 0, //数据索引
    swiperIndex: 0, //swiper索引
    swiperItems: [],
    selectedresults: {},
    score: 0,
    StorageAll: {},
    indexInd: 0,
    redNum: 0,
    greenNum: 0,
    allNum: 0,
    intensify_qis: [],
    intensify_eids: [],
    intensify_okids: [],
    orderPX: {},
    idarr: [],
    textTab: "答题模式",
    selectInd: !0,

    iconcircle: [],
    recmend: !1,
    youind: 0,
    outside: !0,
    current: 0,
    questions: [],
    timeshow: !0,
    times: "",
    ytimes: "",
    danxuan: 0,
    duoxuan: 0,
    panduan: 0,
    allfen: 0,
    passf: 0,
    interval: 300,
    training_qids: "",
    training_jl: "",
    videoctrl: !0,
    videoMedia: "",
    startTime: 0,
    startTimeind: !1,
    nums: 0,
    testMode: !1,
    selectedMap:{

    },
  },

  onLoad: function (options) {
    console.log('options');
    console.log(options);
    this.onGetOpenid();
    this.get(options.exam);
    let ordernum = this.generate();
    this.setData({
      examid: options.exam,
      ordernum,
      times: "45:00",
    });
    wx.setNavigationBarTitle({
      title: "答题助手"
    });
    this.timeServal(44);
    
  },
  generate: function(){
    return util.formatTime(new Date());
  },
  onReady: function () {

  },

  onShow: function () {
    var that = this;
    wx.getUserInfo({
      success: function (res) {
        that.setData({
          userInfo: res.userInfo
        })
      }
    });
  },

  

  selectAnswer: function(t){
    console.log('selectAnswer');
    console.log(app.globalData.questions);
    console.log(t);
    console.log(t.currentTarget.dataset);
    let item = JSON.parse(t.currentTarget.dataset.value);
    if(item.selected){
      return;
    }
    item.selected = true;

    let code = t.currentTarget.dataset.code;
    let answer = t.currentTarget.dataset.answer;
    let options = item.options;

    let greenNum = this.data.greenNum;
    let redNum = this.data.redNum;
    let selectedMap = this.data.selectedMap;
    item.right = 0;
    options.map(o => {
      o.selected = false;
      if(o.code == code){
        o.selected = true;
      }
      if((o.code == code)&&(o.value == 1)){
        greenNum++;
        item.right = 1;
        selectedMap[item.index] = 1;
      }
      if((o.code == code)&&(o.value == 0)){
        redNum++;
        item.right = 0;
        selectedMap[item.index] = 0;
        this.addNote(item);
      }
    })
    console.log(item);
    console.log('111');
    console.log(this.data.arr);
    console.log(selectedMap);
    item.options = options;

    app.globalData.questions[this.data.currIndex] = item;


    let newSwiperItems = [];
    this.data.swiperItems.map((ele) => {
      let index = ele.index;
      console.log('更新：'+index);
      if(index == item.index){
        ele = item;
      }
      newSwiperItems.push(ele);
    })

    this.setData({
      greenNum: greenNum,
      redNum: redNum,
      selectedMap,
      swiperItems: newSwiperItems
    })
    if(this.data.currIndex == app.globalData.questions.length - 1){
      console.log(this.data.currIndex,app.globalData.questions.length)
      this.result();
    }else{
      // this.autoPlay();
    }

  },
  addHistory: function(){
    let that = this;
    let ordernum = this.data.ordernum;
    let questions = app.globalData.questions;
    let arr = [];
    questions.forEach((q)=>{
      if(q.selected){
        arr.push(q);
      }
    })
    const db = wx.cloud.database()
    db.collection('historys').add({
      data: {
        _id: ordernum,
        time: this.data.ytimes,
        md5,
        questions,
        nums: this.data.greenNum*10,
        userInfo: app.globalData.userInfo
      },
      success: res => {
        console.log('[数据库] [新增记录] 成功，记录 _id: ', res._id)
        // 在返回结果中会包含新创建的记录的 _id
        // wx.showToast({
        //   title: '新增记录成功',
        // })
      },
      fail: err => {
        wx.showToast({
          icon: 'none',
          title: '新增记录失败'
        })
        console.error('[数据库] [新增记录] 失败：', err)
      }
    })
  },
  addNote: function(ques){
    let that = this;
    let ordernum = this.data.ordernum;
    const db = wx.cloud.database()
    db.collection('notes').add({
      data: {
        examid: this.data.examid,
        ordernum: ordernum,
        question: ques
      },
      success: res => {
        console.log('[数据库] [新增记录] 成功，记录 _id: ', res._id)
        // 在返回结果中会包含新创建的记录的 _id
        // wx.showToast({
        //   title: '新增记录成功',
        // })
      },
      fail: err => {
        wx.showToast({
          icon: 'none',
          title: '新增记录失败'
        })
        console.error('[数据库] [新增记录] 失败：', err)
      }
    })
  },

  autoPlay: function () {
    console.log('autoplay');
    this.setData({
      autoplay: true
    });

  },

  pageChange: function (e) {
    console.log('pageChange');
    console.log(e.detail);

    console.log('[滑动]');
    console.log(this.data.currIndex);
    console.log(app.globalData.questions.length);
   

    //更新swiper索引
    let newCurrent = e.detail.current;
    let oldCurrent = this.data.swiperIndex;
    this.data.swiperIndex = newCurrent;

    //更新数据索引
    if (newCurrent === oldCurrent + 1 || oldCurrent + 1 === this.data.swiperItems.length + newCurrent) { //正向
      console.log('正向')
      this.data.currIndex++;
    } else { //逆向
      console.log('逆向')
      this.data.currIndex--;
    }

    //数据索引边界处理
    if (this.data.currIndex > app.globalData.questions.length - 1) {
      this.data.currIndex = 0;
    } else if (this.data.currIndex < 0) {
      this.data.currIndex = app.globalData.questions.length - 1;
    }


    let swiperItems = this.data.swiperItems;
    
    //确定三个item的数据值
    let curr = app.globalData.questions[this.data.currIndex]
    let next = this.data.currIndex === app.globalData.questions.length - 1 ? 0 : app.globalData.questions[this.data.currIndex + 1];
    let pre = this.data.currIndex === 0 ? app.globalData.questions[app.globalData.questions.length - 1] : app.globalData.questions[this.data.currIndex - 1];

    
    //当前item不用处理，其他两个item更新显示；
    if (this.data.swiperIndex === 0) {
      swiperItems[1] = next;
      swiperItems[2] = pre;
    } else if (this.data.swiperIndex === 1) {
      swiperItems[0] = pre;
      this.data.swiperItems[2] = next;
    } else if (this.data.swiperIndex === 2) {
      swiperItems[0] = next;
      swiperItems[1] = pre;
    }
    
    
    this.setData({
      currIndex: this.data.currIndex,
      swiperItems: swiperItems,
      circular: true,
      me:[],
      starshow: false,
      autoplay: false
    },()=>{
      console.log(this.data.swiperItems);
    })
  },

  newUp_exam:function() {
    console.log(this.data.allNum);
    this.result();
  },

  changeTab:function() {
    var e = this,
    a = e.data.questions;
    e.setData({
      questions: a,
      textTab:"背题模式",
      selectInd: !1
    })
  },

  random: function () {
    var r = this;
    s = r.data.category.id;
    console.log(n + "" + s)
    wx.getStorage({
      key: n + "" + s,
      success: function (t) {
        console.log(t)
        r.setData({
          StorageAll: t.data
        });
        console.log(t.data)
      },
      complete: function () {
        var t = q.questionIds["questionId"]
        var question = q.questions["question"]
        var question_ids = r.getRandomArrayElements(t, 100)
        console.log(question_ids)
      }
    })
  },

  getRandomArrayElements(arr,count){
    var shuffled = arr.slice(0),
      i = arr.length,
      min = i - count,
      temp,index;
    while ( i-- > min){
      index = Math.floor((i + 1) * Math.random());
      temp = shuffled[index];
      shuffled[index] = shuffled[i];
      shuffled[i] = temp;
    }

    return shuffled.slice(min);
  },

  timeServal: function (t) {
    console.log(t)
    if (0 != t) {
      var e = t,
        a = 59,
        n = this;
      setInterval(function () {
        a < 10 ? n.setData({
          times: e + ":0" + a,
          ytimes: t - e + ":" + (59 - a)
        }) : n.setData({
          times: e + ":" + a,
          ytimes: t - e + ":" + (59 - a)
        }), --a < 0 && (e > 0 ? (a = 59, e--) : (a = 0, e = 0, n.setData({
          startTimeind: !0
        })));
      }, 1e3);
    } else this.setData({
      times: 0,
      startTimeind: !0
    });
  },


  result: function () {
    this.addHistory();
    let questions = this.data.questions;
    let allNum = 0;
    wx.setStorage({
      key: "questionArr",
      data: this.data.questions
    });
    if(this.data.examid == '001'){
      this.updateProfileS1(this.data.greenNum*1);
    }
    if(this.data.examid == '002'){
      this.updateProfileS1(this.data.greenNum*2);
    }
    wx.navigateTo({
      url: "../examresult/examresult?examid="+this.data.examid+"&ordernum="+this.data.ordernum+"&times="+ this.data.times  +"&greenNum=" + this.data.greenNum + "&redNum=" + this.data.redNum + "&allNum=" + allNum + "&ytimes=" + this.data.ytimes + "&allfen=" + this.data.allfen  + "&allQuestionCount=" + this.data.nums,
    })
  },

  onUnload: function () {

  },

  onHide: function () {
  },

  onGetOpenid: function() {
    let that = this;
    // 调用云函数
    wx.cloud.callFunction({
      name: 'login',
      data: {},
      success: res => {
        console.log('[云函数] [login]: ', res)
        app.globalData.openid = res.result.openid
        that.setData({
          openid: res.result.openid
        })
        // wx.navigateTo({
        //   url: '../userConsole/userConsole',
        // })
      },
      fail: err => {
        console.error('[云函数] [login] 调用失败', err)
        wx.navigateTo({
          url: '../deployFunctions/deployFunctions',
        })
      }
    })
  },
  get: function(examid) {
    let that = this;
  
    try {
      var arr = wx.getStorageSync('arr');
      if (arr) {
        console.log('出题');
        console.log(arr);
        // Do something with return value
        // 调用云函数
        wx.cloud.callFunction({
          name: 'get',
          data: {
            examid: examid
          },
          success: res => {
            console.log('[云函数] [get]: ', res)
            let items = res.result.data;
            let newItems = items.filter(item => arr.indexOf(item._id)!=-1);
            console.log(items);
            console.log(newItems);
            let questions = [];
            let selectedMap = this.data.selectedMap;
            newItems.forEach((item, idx) =>{
              
              item.index = idx;
              item.right = -1;
              let options = item.options;
              let formatedOptions = [];
              options.forEach((option)=>{
                option.selected = false;
                option.value = parseInt(option.value);
                formatedOptions.push(option)
              })
              item.options = formatedOptions;
              item.selected = false;
              questions.push(item);
              selectedMap[idx] = -1;
            })
            console.log('selectedMap');
            console.log(selectedMap);
            app.globalData.questions = questions;
            let swiperItems = questions.slice(0,3);
            console.log(swiperItems);
            this.setData({
              // questions
              selectedMap,
              arr,
              nums: questions.length,
              swiperItems,
            },()=>{
              console.log(this.data);
            })
          },
          fail: err => {
            console.error('[云函数] [login] 调用失败', err)
            wx.navigateTo({
              url: '../deployFunctions/deployFunctions',
            })
          }
        })
      }
    } catch (e) {
      // Do something when catch error
    }

    
  },
  _updown: function () {
    var t = this;
    this.setData({
      iconInd: !this.data.iconInd,
      iconIndtwo: !this.data.iconIndtwo
    });
    console.log(this.data.iconInd)
  },
  updateProfileS1: function(num){
    let that = this;
    let openid = app.globalData.openid;
    const db = wx.cloud.database();
    const _ = db.command;
    db.collection('profiles').doc(openid).update({
      data: {
        // 表示指示数据库将字段自增 10
        s1:num
      },
      success: function(res) {
        console.log(res)
      }
    })
  },
  updateProfileS4: function(num){
    let that = this;
    let openid = app.globalData.openid;
    const db = wx.cloud.database();
    const _ = db.command;
    db.collection('profiles').doc(openid).update({
      data: {
        // 表示指示数据库将字段自增 10
        s4:num
      },
      success: function(res) {
        console.log(res)
      }
    })
  }
})